package repository

import (
	"GIN-API/internal/models"
	"errors"
	"gorm.io/gorm"
)

type ChannelRepository struct {
	db *gorm.DB
}

func NewChannelRepo(db *gorm.DB) *ChannelRepository {
	return &ChannelRepository{db: db}
}

// CreateChannel 创建频道
func (cr *ChannelRepository) CreateChannel(channel *models.Channel) error {
	return cr.db.Create(channel).Error
}

// GetChannelByID 根据频道 ID 获取频道信息
func (cr *ChannelRepository) GetChannelByID(id uint) (*models.Channel, error) {
	var channel models.Channel
	err := cr.db.First(&channel, id).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, err
	}
	return &channel, nil
}

// UpdateChannel 更新频道信息
func (cr *ChannelRepository) UpdateChannel(channel *models.Channel) error {
	return cr.db.Model(channel).Updates(channel).Error
}

// DeleteChannel 根据频道 ID 删除频道
func (cr *ChannelRepository) DeleteChannel(id uint) error {
	return cr.db.Delete(&models.Channel{}, id).Error
}

// GetAllChannels 获取所有频道
func (cr *ChannelRepository) GetAllChannels() ([]*models.Channel, error) {
	var channels []*models.Channel
	err := cr.db.Find(&channels).Error
	if err != nil {
		return nil, err
	}
	return channels, nil
}
